<template>

  <li
    class="tree-item draggable handle"
    :class="{expand: isExpand, 'no-child': !treeItemData[childrenKey] || treeItemData[childrenKey].length === 0}"
    :title="treeItemData[nameKey]"
    @dragstart="dragstart_handler"
  >
    <div class="tree-content" @click="_clickEvent">
      <div class="expand-arrow" @click.stop="expandTree()">
        <a-icon :component="require('@/assets/icon/arrow_down.svg')" />
      </div>
      <div
        class="tree-label text-over"
        :class="{'no-child': !treeItemData[childrenKey] || treeItemData[childrenKey].length === 0}"
      >{{ treeItemData[nameKey] }}</div>
    </div>
    <ul v-if="treeItemData[childrenKey] && treeItemData[childrenKey].length > 0" class="sub-tree">
      <draggable
        class="d-flex flex-column tag-box-ul"
        :list="treeItemData[childrenKey]"
        :group="{ name: 'people', pull: 'clone', put: false }"
        :clone="cloneDog"
      >
        <!-- 递归 -->
        <TreeItem
          v-for="(item,index) in treeItemData[childrenKey]"
          :key="uuid()+index"
          :tree-item-data="item"
          :clone-dog="cloneDog"

          :name-key="nameKey"
          :children-key="childrenKey"
        />
      </draggable>
    </ul>

  </li>

</template>

<script>
import draggable from 'vuedraggable';
export default {
  name: 'TreeItem',
  components: {
    draggable
  },
  props: {
    treeItemData: {
      type: Object,
      default() {
        return {};
      }
    },
    nameKey: {
      type: String,
      default: 'text'
    },
    childrenKey: {
      type: String,
      default: 'ftmAtaChapter'
    },
    // // 节点点击事件
    cloneDog: {
      type: Function,
      default() {
        return function() {};
      }
    }
  },
  data() {
    return {
      // 节点是否展开
      isExpand: this.treeItemData.expand || false
    };
  },

  methods: {
    dragstart_handler(ev) {
      ev.dataTransfer.setDragImage(ev.target.children[0], 0, 0);
    },
    // 展开/收缩
    expandTree(flag) {
      if (!this.treeItemData[this.childrenKey] || this.treeItemData[this.childrenKey].length === 0) {
        return;
      }
      if (typeof flag === 'undefined') {
        flag = !this.isExpand;
      } else {
        flag = !!flag;
      }
      this.isExpand = flag;
    },
    // 创建一个唯一id
    uuid() {
      let str = Math.random().toString(32);
      str = str.substr(2);
      return str;
    },

    // 节点点击事件
    _clickEvent() {
      // 如果有传递事件函数，则调用事件函数并传递当前节点数据及组件
      if (this.treeClickEvent && typeof this.treeClickEvent === 'function') {
        this.treeClickEvent(this.treeItemData, this);
      }
    }
  }
};
</script>
